package com.zhuj.server;

import com.zhuj.core.InitNrpc;
import com.zhuj.core.annotation.NrpcService;
import com.zhuj.core.util.AssistUtil;
import com.zhuj.core.util.StringUtil;
import com.zhuj.register.Register;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/9.
 */
public class ServiceRegistry {

    private ServiceRegistry(){}

    public static ServiceRegistry getInstance(){
        return LazyHolder.serviceRegistry;
    }

    private static class LazyHolder{
        private static ServiceRegistry serviceRegistry = new ServiceRegistry();
    }

    private Map<String,Object> services = new HashMap<String, Object>();

    public void registryByNative(String scanPackage) throws Exception {
        String[] scanPackages = scanPackage.split(",");
        for (String scan:scanPackages){
            for(String className: AssistUtil.getClassName(scan,true)){
                Class clazz = AssistUtil.getClass(className);
                if (clazz.getAnnotation(NrpcService.class)!=null) {
                    services.put(StringUtil.lastSubCharStr(clazz.getInterfaces()[0].toString(),"."),clazz.newInstance());
                }
            }
        }
        if (InitNrpc.getRedisAddress()!=null){
            Register.registerService(services.keySet(),InitNrpc.getPort());
        }
    }

    public void registryBySpring(Object[] beans) throws Exception {
        for (Object bean:beans){
            Class clazz = bean.getClass();
            if (clazz.getAnnotation(NrpcService.class)!=null) {
                services.put(StringUtil.lastSubCharStr(clazz.getInterfaces()[0].toString(),"."),bean);
            }
        }
        if (InitNrpc.getRedisAddress()!=null){
            Register.registerService(services.keySet(),InitNrpc.getPort());
        }
    }

    public boolean isEmpty(){
        return services.isEmpty();
    }

    public Object getService(String serviceName){
        return services.get(serviceName);
    }

}
